<?php


namespace app\api\library\order\createOrder;

use app\api\model\MallCollage;
use app\api\model\MallOrder;
use app\api\model\MallUser;
use Exception;
use think\facade\Db;

class V
{
    public static function run($param)
    {
        $userId      = _checkEmptyParam($param[ 'userId' ], '用户ID不能为空');
        $goodsId     = _checkEmptyParam($param[ 'goodsId' ], '商品ID不能为空');
        $specId      = _checkEmptyParam($param[ 'specId' ], '规格ID不能为空');
        $shareUserId = $param[ 'shareUserId' ];
        $collageId   = $param[ 'collageId' ];
        $goods       = Db::name('mall_goods')->where('id', $goodsId)->find();
        $spec        = Db::name('mall_goods_spec')->where('spec_id', $specId)->find();
        $isNovice    = MallUser::where('id', $userId)->value('is_novice');
        if ($goods[ 'is_novices_exclusive' ] == 1 && $isNovice != 1) {
            _outPut(201, [], '该商品只允许新手购买');
        }
        if ($goods[ 'buy_num' ] > 0) {
            $buyNum = MallOrder::where([['user_id', '=', $userId], ['goods_id', '=', $goodsId], ['order_status', '>', 0]])->value('count(1)');
            if ($buyNum >= $goods[ 'buy_num' ]) {
                _output(204, [], '该商品只允许购买' . $goods[ 'buy_num' ] . '次，您已达购买上限');
            }
        }
        if (empty($goods)) {
            _outPut(204, '', '商品不存在');
        }
        if ($collageId) {
            $collage = Db::name('mall_collage')->where([['collage_id', '=', $collageId]])->find();
            if ($collage[ 'fail_time' ] > 0 || $collage[ 'status' ] == 0) {
                _output(204, [], '该拼团已失败，请返回首页');
            }
            if ($collage[ 'finish_time' ] > 0) {
                _output(204, [], '该拼团已完成，请返回首页查看其它商品');
            }
            $collageOrder  = MallOrder::where([['user_id', '=', $userId], ['order_status', 'in', [10, 30, 50, 60]], ['collage_id', '=', $collageId]])->find();
            $uCollageOrder = MallOrder::where([['user_id', '=', $userId], ['order_status', 'in', [10, 30, 50, 60]], ['u_collage_id', '=', $collageId]])->find();
            if ( !empty($collageOrder) || !empty($uCollageOrder)) {
                _output(204, [], '您已参与该拼团');
            }
            $originalCollageId = MallOrder::where([['order_status', 'in', [10, 30, 50, 60]], ['collage_id', '=', $collageId]])->value('u_collage_id');
            if ( !empty($originalCollageId)) {
                $collageOrder = MallOrder::where([['user_id', '=', $userId], ['order_status', 'in', [10, 30, 50, 60]], ['collage_id', '=', $originalCollageId]])->find();
                if ( !empty($collageOrder)) {
                    _output(204, [], '该拼团是您的参与人，不能加入');
                }
            }
        }
        try {
            //开启事务
            Db::startTrans();
            $orderNo  = createOrderNo();
            $addOrder = [
                'order_no'     => $orderNo,
                'user_id'      => $userId,
                'goods_id'     => $goodsId,
                'goods_name'   => $goods[ 'title' ],
                'spec_id'      => $spec[ 'spec_id' ],
                'spec_name'    => $spec[ 'name' ],
                'total_price'  => $goods[ 'market_price' ],
                'order_price'  => $goods[ 'discount_price' ],
                'uid'          => $shareUserId,
                'u_collage_id' => $collageId,
                'create_time'  => time(),
                'update_time'  => time(),
            ];
//            if ($isNovice == 1 && $goods[ 'is_novices_exclusive' ] == 1) {
//                $addOrder[ 'order_price' ] = $goods[ 'novice_price' ];
//            }
            $orderId = Db::name('mall_order')->insertGetId($addOrder);
            if (false === $orderId) {
                _throwNewException('创建订单失败');
            }
            Db::commit();
            $order            = Db::name('mall_order')->field('id,goods_id,order_no,order_price,order_status,create_time')->find($orderId);
            $order[ 'goods' ] = Db::name('mall_goods')
                ->where([['id', '=', $order[ 'goods_id' ]]])
                ->field('id,title,logo,remark')
                ->find();
            _outPut(200, $order);
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            _output(204, [], $e->getMessage());
        }
    }
}